package com.lyl.xxx.common.aspect;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.lyl.common.util.ContextHolderUtil;
import com.lyl.xxx.common.annotation.Log;
import com.lyl.xxx.common.enums.BusinessStatus;
import com.lyl.xxx.common.utils.AddressUtils;
import com.lyl.xxx.common.utils.IpUtils;
import com.lyl.xxx.modules.framework.security.model.details.LoginDetails;
import com.lyl.xxx.modules.framework.security.utils.SecurityUtil;
import com.lyl.xxx.modules.system.account.entity.SysOperLog;
import com.lyl.xxx.modules.system.account.entity.SysUser;
import com.lyl.xxx.modules.system.account.service.SysOperLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * 操作日志记录处理
 *
 * @author ruoyi
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {
    private final Executor logExecutor;
    private final SysOperLogService sysOperLogService;

    /**
     * 排除敏感属性字段
     */
    protected static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        //初始化接口操作日志
        SysOperLog operLog = initSysOperLog(joinPoint, null);
        CompletableFuture.runAsync(
                        () -> handleLog(joinPoint, controllerLog, operLog, jsonResult),
                        logExecutor)
                .exceptionally(ex -> {
                    log.error("操作日志保存异常: ", ex);
                    return null;
                });
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        //初始化接口操作日志
        SysOperLog operLog = initSysOperLog(joinPoint, e);
        //异步保存日志
        CompletableFuture.runAsync(
                        () -> handleLog(joinPoint, controllerLog, operLog, null),
                        logExecutor)
                .exceptionally(ex -> {
                    log.error("操作日志保存异常: ", ex);
                    return null;
                });
    }

    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, SysOperLog operLog, Object jsonResult) {
        try {
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
            // 保存数据库
            operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
            sysOperLogService.save(operLog);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    private SysOperLog initSysOperLog(JoinPoint joinPoint, Exception e) {
        // 获取当前的用户
        LoginDetails details = SecurityUtil.getLoginDetails();
        SysUser loginUser = details.getSysUser();

        // *========数据库日志=========*//
        SysOperLog operLog = new SysOperLog();
        operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
        // 请求的地址
        HttpServletRequest request = ContextHolderUtil.getRequest();
        String ip = IpUtils.getIpAddr(request);
        operLog.setOperIp(ip);
        assert request != null;
        operLog.setOperUrl(CharSequenceUtil.sub(request.getRequestURI(), 0, 255));
        if (loginUser != null) {
            operLog.setOperName(loginUser.getUserName());
        }

        if (e != null) {
            operLog.setStatus(BusinessStatus.FAIL.ordinal());
            operLog.setErrorMsg(CharSequenceUtil.sub(e.getMessage(), 0, 2000));
        }
        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        operLog.setMethod(className + "." + methodName + "()");
        // 设置请求方式
        operLog.setRequestMethod(request.getMethod());
        return operLog;
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log     日志
     * @param operLog 操作日志
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) {
        // 设置action动作
        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setTitle(log.title());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog);
        }
        // 是否需要保存response，参数和值
        if (log.isSaveResponseData() && ObjectUtil.isNotEmpty(jsonResult)) {
            operLog.setJsonResult(CharSequenceUtil.sub(JSON.toJSONString(jsonResult), 0, 2000));
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(CharSequenceUtil.sub(params, 0, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) Objects.requireNonNull(ContextHolderUtil.getRequest()).getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operLog.setOperParam(CharSequenceUtil.sub(paramsMap.toString(), 0, 2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (ObjectUtil.isNotEmpty(o) && !isFilterObject(o)) {
                    try {
                        String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter());
                        params.append(jsonObj).append(" ");
                    } catch (Exception ignored) {
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 忽略敏感属性
     */
    public SimplePropertyPreFilter excludePropertyPreFilter() {
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().addAll(Arrays.asList(EXCLUDE_PROPERTIES));
        return filter;
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            return CollUtil.getFirst(collection) instanceof MultipartFile;
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            return CollUtil.getFirst(map.values()) instanceof MultipartFile;
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
